package yd.launcher;

import yd.launcher.service.Action;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.util.Enumeration;

/**
 * 用于编辑action
 */
public class ActionEditDialog extends JDialog {
    private JComponent component;

    private JTextField nameTextField;
    private JTextArea commandTextArea;
    private JButton filePathChooseButton;
    private JCheckBox showCommandWindowCheckBox;
    private ButtonGroup workingDirectoryOptionGroup;

    private JButton okButton,resetButton,cancelButton;//底部操作按钮

    // 构造函数，设置对话框的基本属性
    public ActionEditDialog(JComponent component) {
        super((JFrame)null, true);
        this.component = component;

        initFormComponents();
        arrangeFormComponents();
        initButtonPanel();
        initData();
        // 自动调整对话框大小以适应其内容
        pack();
        // 设置对话框居中显示
        setLocationRelativeTo(null);
        // 设置默认关闭操作（可选）
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    // 创建包含表单字段的面板
    private void initFormComponents() {
        nameTextField = new JTextField();
        R.textUndoManager.put(nameTextField);
        commandTextArea = new JTextArea();
        commandTextArea.setLineWrap(true);
        commandTextArea.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                filePathChooseButton.setFocusPainted(true);
            }

            @Override
            public void focusLost(FocusEvent e) {
                filePathChooseButton.setFocusPainted(true);
            }
        });
        R.textUndoManager.put(commandTextArea);
        filePathChooseButton = new JButton("选择路径");
        filePathChooseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showDialog(ActionEditDialog.this, "选择");
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    commandTextArea.append(selectedFile.getAbsolutePath());
                }
            }
        });
        showCommandWindowCheckBox = new JCheckBox("显示命令窗口");
        workingDirectoryOptionGroup = new ButtonGroup();
    }

    private void arrangeFormComponents(){
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
        add(formPanel, BorderLayout.CENTER);

        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.weightx=1;
        formPanel.add(new JLabel("名称"), gridBagConstraints);
        gridBagConstraints.gridy = 1;
        formPanel.add(new JLabel("执行命令"), gridBagConstraints);
        gridBagConstraints.gridy=2;
        formPanel.add(new JLabel("附加选项"),gridBagConstraints);

        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.weightx=5;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        formPanel.add(nameTextField, gridBagConstraints);

        gridBagConstraints.gridy = 1;
        JPanel panel=new JPanel();
        SpringLayout springLayout = new SpringLayout();
        panel.setLayout(springLayout);
        panel.setPreferredSize(new Dimension(0,150));
        formPanel.add(panel, gridBagConstraints);

        panel.add(filePathChooseButton);
        springLayout.putConstraint(SpringLayout.EAST, filePathChooseButton, -15, SpringLayout.EAST, panel);
        springLayout.putConstraint(SpringLayout.SOUTH, filePathChooseButton, -5, SpringLayout.SOUTH, panel);

        JScrollPane scrollPane = new JScrollPane(commandTextArea);
        //scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        panel.add(scrollPane);
        springLayout.putConstraint(SpringLayout.WEST,scrollPane,0,SpringLayout.WEST,panel);
        springLayout.putConstraint(SpringLayout.EAST,scrollPane,0,SpringLayout.EAST,panel);
        springLayout.putConstraint(SpringLayout.NORTH,scrollPane,0,SpringLayout.NORTH,panel);
        springLayout.putConstraint(SpringLayout.SOUTH,scrollPane,0,SpringLayout.SOUTH,panel);

        gridBagConstraints.gridy = 2;

        Box box = Box.createVerticalBox();
        formPanel.add(box, gridBagConstraints);
        JPanel checkBoxPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
        box.add(checkBoxPanel);
        checkBoxPanel.add(showCommandWindowCheckBox);
        JPanel radiosPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
        box.add(radiosPanel);
        JLabel jLabel = new JLabel("工作目录：");
        radiosPanel.add(jLabel);
        JRadioButton radio01 = new JRadioButton("本程序", true);
        JRadioButton radio02 = new JRadioButton("启动程序");
        JRadioButton radio03 = new JRadioButton("目标文件");
        radio02.setToolTipText("取自命令的第一段");
        radio03.setToolTipText("取自命令的最后一段");
        radio01.setActionCommand("1");
        radio02.setActionCommand("2");
        radio03.setActionCommand("3");
        workingDirectoryOptionGroup.add(radio01);
        workingDirectoryOptionGroup.add(radio02);
        workingDirectoryOptionGroup.add(radio03);
        radiosPanel.add(radio01);
        radiosPanel.add(radio02);
        radiosPanel.add(radio03);
        //radiosPanel.setAlignmentX(Box.LEFT_ALIGNMENT);

        Box verticalBox = Box.createVerticalBox();
        verticalBox.add(Box.createHorizontalGlue());
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.weighty = 1;
        gridBagConstraints.anchor = GridBagConstraints.CENTER;
        formPanel.add(verticalBox, gridBagConstraints);
    }

    // 创建包含确定和取消按钮的面板
    private void initButtonPanel() {
        JPanel buttonPanel = new JPanel();
        ((FlowLayout)buttonPanel.getLayout()).setAlignment(FlowLayout.RIGHT);
        add(buttonPanel, BorderLayout.SOUTH);

        okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (component instanceof ButtonsPanel) {
                    ((ButtonsPanel) component).addNewAction(getAction());
                } else if (component instanceof JButton) {
                    Action action = getAction();
                    JButton button = (JButton) component;
                    button.setText(action.getName());
                    ((ButtonsPanel) button.getParent()).editAction(Integer.valueOf(button.getActionCommand()), action);
                }
                dispose();
            }
        });
        buttonPanel.add(okButton);

        resetButton = new JButton("Reset");
        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                nameTextField.setText(null);
                commandTextArea.setText(null);
                showCommandWindowCheckBox.setSelected(false);
                workingDirectoryOptionGroup.clearSelection();
            }
        });
        buttonPanel.add(resetButton);

        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        buttonPanel.add(cancelButton);
    }

    private void initData() {
        if (component instanceof ButtonsPanel) {
            setTitle("Add New Launcher");
        } else if (component instanceof JButton) {
            setTitle("Edit Launcher: 【" + ((JButton) component).getText()+"】");
            JButton button = (JButton) component;
            Action action = ((ButtonsPanel)button.getParent()).getAction(Integer.valueOf(button.getActionCommand()));
            setAction(action);
        }
    }
    private void setAction(Action action) {
        nameTextField.setText(action.getName());
        commandTextArea.setText(action.getCommand());
        showCommandWindowCheckBox.setSelected(action.isShowCommandWindow());
        Enumeration<AbstractButton> elements = workingDirectoryOptionGroup.getElements();
        while (elements.hasMoreElements()) {
            AbstractButton button = elements.nextElement();
            if (Integer.valueOf(button.getActionCommand()) == action.getWorkingDirectoryOption()) {
                button.setSelected(true);
            }
        }

    }
    private Action getAction(){
        int workingDirectoryOption = Integer.valueOf(workingDirectoryOptionGroup.getSelection().getActionCommand());
        return new Action(nameTextField.getText(),commandTextArea.getText(),showCommandWindowCheckBox.isSelected(),workingDirectoryOption);
    }

}
